package com.ruoyi.demo.service.impl;




import com.ruoyi.demo.pojo.Result;
import com.ruoyi.demo.service.ITwsService;
import com.ruoyi.demo.sign.LfasrSignature;
import com.ruoyi.demo.util.HttpUtil;
import com.ruoyi.demo.util.MinIOUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;



import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.security.SignatureException;
import java.util.HashMap;

@Service
public class ITwsServiceImpl implements ITwsService {

    private final boolean dev = false;
    @Value("${tws.ifasr.host}")
    private String HOST;
    @Value("${tws.ifasr.appid}")
    private String appid;
    @Value("${tws.ifasr.keySecret}")
    private String keySecret;
    // Python 服务地址
    @Value("${flask.host}")
    private String pythonServiceUrl;
    // Http发送
    @Autowired
    private RestTemplate restTemplate;

    //Minio工具类
    @Autowired
    private MinIOUtil minIOUtil = new MinIOUtil();

    private String getResult(String orderId) throws SignatureException, InterruptedException, IOException, JSONException {
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("orderId", orderId);
        LfasrSignature lfasrSignature = new LfasrSignature(appid, keySecret);
        map.put("signa", lfasrSignature.getSigna());
        map.put("ts", lfasrSignature.getTs());
        map.put("appId", appid);
        map.put("resultType", "transfer,predict");
        String paramString = HttpUtil.parseMapToPathParam(map);
        String url = HOST + "/v2/api/getResult" + "?" + paramString;
        if (dev) {
            System.out.println("\nget_result_url:" + url);
        }
        while (true) {
            String response = HttpUtil.iflyrecGet(url);
            JSONObject resultJson = new JSONObject(response);
            String contentStr = resultJson.getString("content");
            JSONObject contentJson = new JSONObject(contentStr);
            String orderInfoStr = contentJson.getString("orderInfo");
            JSONObject orderInfoJson = new JSONObject(orderInfoStr);
            int status = orderInfoJson.getInt("status");
            if (status == 4 || status == -1) {
                if (dev) {
                    System.out.println("订单完成:" + response);
                }
                String translate = extractWordsFromOrderResult(response);
                return translate;
            } else {
                if (dev) {
                    System.out.println("进行中...，状态为:" + status);
                }
                //建议使用回调的方式查询结果，查询接口有请求频率限制
                Thread.sleep(7000);
            }
        }
    }


    private String extractWordsFromOrderResult(String jsonString) {
        try {
            // 解析最外层的 JSON
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject content = jsonObject.getJSONObject("content");
            String orderResult = content.getString("orderResult");

            // 解析 orderResult 字符串为 JSON 对象
            JSONObject orderResultJson = new JSONObject(orderResult);
            JSONArray lattice = orderResultJson.getJSONArray("lattice");

            // 用 StringBuilder 拼接所有的 "w" 字段
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < lattice.length(); i++) {
                JSONObject latticeItem = lattice.getJSONObject(i);
                String json1best = latticeItem.getString("json_1best");

                // 解析 json_1best
                JSONObject json1bestJson = new JSONObject(json1best);
                JSONObject st = json1bestJson.getJSONObject("st");
                JSONArray rt = st.getJSONArray("rt");

                // 遍历 rt 数组，拼接所有 "w" 字段
                for (int j = 0; j < rt.length(); j++) {
                    JSONObject rtItem = rt.getJSONObject(j);
                    JSONArray ws = rtItem.getJSONArray("ws");

                    for (int k = 0; k < ws.length(); k++) {
                        JSONObject wsItem = ws.getJSONObject(k);
                        JSONArray cw = wsItem.getJSONArray("cw");

                        for (int l = 0; l < cw.length(); l++) {
                            JSONObject cwItem = cw.getJSONObject(l);
                            String word = cwItem.getString("w");
                            result.append(word);
                        }
                    }
                }
            }

            // 返回拼接的结果
            return result.toString();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public Result getTwsRemote(String filName, String meet_id) {
        Result result = new Result();
        try {
            String uploadResult = upload(filName, meet_id);
            String jsonStr = StringEscapeUtils.unescapeJavaScript(uploadResult);
            JSONObject jsonObject = new JSONObject(jsonStr);
            String orderId = jsonObject.getJSONObject("content").getString("orderId");
            result = new Result();
            result.setMessage(getResult(orderId));
            result.setStatus("1");
            return result;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            result.setStatus("2");
            result.setMessage("!ERROR: CANNOT USE Remote API ");
            return result;
        }
    }

    public Result getTwsLocal(String fileName, String meet_id) {
        // 构建查询参数
        String targetUrl = UriComponentsBuilder.fromHttpUrl(pythonServiceUrl + "/aitws")
                .queryParam("meet_id", meet_id)
                .queryParam("fileName", fileName)
                .toUriString();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        if (dev) {
            System.out.println("meet_id:" + meet_id + "  fileName:" + fileName);
        }
        // 发送请求到 Python 服务
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<Result> response = restTemplate.exchange(
                targetUrl,
                HttpMethod.GET,
                requestEntity,
                Result.class
        );
        return response.getBody();
    }

    private String upload(String fileName, String meet_id) throws SignatureException, IOException {
        HashMap<String, Object> map = new HashMap<>(16);

//        获取文件
        MultipartFile audio = minIOUtil.getMeetAudio(fileName, meet_id);

        InputStream inputStream = audio.getInputStream();
        long fileSize = audio.getSize();

//        设置请求参数
        map.put("appId", appid);
        map.put("fileSize", fileSize);
        map.put("fileName", fileName);
        map.put("duration", "200");
        LfasrSignature lfasrSignature = new LfasrSignature(appid, keySecret);
        map.put("signa", lfasrSignature.getSigna());
        map.put("ts", lfasrSignature.getTs());

        String paramString = HttpUtil.parseMapToPathParam(map);
        if (dev) {
            System.out.println("upload paramString:" + paramString);
        }
        String url = HOST + "/v2/api/upload" + "?" + paramString;
        if (dev) {
            System.out.println("upload_url:" + url);
        }
        String response = HttpUtil.iflyrecUpload(url, inputStream);
        if (dev) {
            System.out.println("upload response:" + response);
        }
        return response;
    }
}
